﻿using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using QQ2564874169.Core.Json.Newtsjson;

namespace QQ2564874169.Core.Utils
{
    public static class JsonHelper
    {
        private static JsonSerializerSettings _settings;

        static JsonHelper()
        {
            _settings = new JsonSerializerSettings
            {
                ContractResolver = new JsonContractResolver(),
                DateFormatString = "yyyy-MM-dd HH:mm:ss.fffffff"
            };
            _settings.Converters.Add(new LongToStringConverter());
            _settings.Converters.Add(new IPAddressToStringConverter());
        }

        public static string ToJson(object obj)
        {
            return JsonConvert.SerializeObject(obj, _settings);
        }

        public static object JsonTo(string json, Type type, bool throwEx = false)
        {
            if (string.IsNullOrEmpty(json))
                return null;
            try
            {
                if (type == typeof(DateTime) && !json.StartsWith("\"") && !json.StartsWith("'"))
                {
                    json = "\"" + json + "\"";
                }
                return JsonConvert.DeserializeObject(json, type);
            }
            catch (Exception)
            {
                if (throwEx)
                    throw;
                return null;
            }
        }

        public static T JsonTo<T>(string json, bool throwEx = false)
        {
            try
            {
                var obj = JsonTo(json, typeof(T), throwEx);
                if (obj != null)
                    return (T) obj;
                return default(T);
            }
            catch
            {
                if (throwEx)
                    throw;
                return default(T);
            }
        }

        public static dynamic JsonTo(string json, bool throwEx = false)
        {
            try
            {
                return JObject.Parse(json);
            }
            catch
            {
                if (throwEx)
                    throw;
                return null;
            }
        }
    }
}
